<?php

namespace apiend\modules\user\controllers;

use Yii;
use apiend\components\Controller;
use common\helpers\ArrayHelper;
use common\helpers\Url;
use common\models\user\UserConnect;
use apiend\modules\user\models\ThirdPartyRelieveForm;

/**
 * 第三方相关接口
 * ThirdPartyController
 */
class ThirdPartyController extends Controller {

    /**
     * Declares the allowed HTTP verbs.
     * Please refer to [[VerbFilter::actions]] on how to declare the allowed verbs.
     * @return array the allowed HTTP verbs.
     */
    protected function verbs() {
        return [
            '*' => ['GET'],
            'relieve' => ['POST'],
        ];
    }

    /**
     * @inheritdoc
     */
    protected function rules() {
        return [
            [
                'allow' => true,
                'roles' => ['@'],
            ],
        ];
    }

    /**
     * 第三方绑定列表
     * @return mixed
     */
    public function actionIndex() {
        $clients = [
            [
                'title' => '微信',
                'client' => 'wechat',
                'bind' => false,
            ],
            [
                'title' => '微博',
                'client' => 'weibo',
                'bind' => false,
            ],
            [
                'title' => 'QQ',
                'client' => 'qq',
                'bind' => false,
            ],
        ];
        $model = UserConnect::findAll([
            'user_id' => $this->uid
        ]);
        $binds = ArrayHelper::getColumn($model, 'client');
        foreach ($clients as $key => $client) {
            $_name = ArrayHelper::getValue($client, 'client');
            $_icon = $_name;
            if (in_array($_name, $binds)) {
                ArrayHelper::setValue($clients, [$key, 'bind'], true);
                $_icon .= '_color';
            }
            ArrayHelper::setValue($clients, [$key, 'icon'], Url::attach('/assets/icons/client/' . $_icon . '.png'));
        }
        return $clients;
    }

    /**
     * 解除第三方账号绑定
     * @return mixed
     */
    public function actionRelieve() {
        $model = new ThirdPartyRelieveForm();
        $model->user_id = $this->uid;
        if (!$model->load(Yii::$app->request->post(), '')) {
            parent::error('参数校验失败');
        }
        return $model->save();
    }

}
